﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;

namespace MvcApplication2.Models
{
    public class AlgoResult
    {
        public IterationResult[] Iterations { get; set; }

        public void ScaleCoordinates()
        {
            foreach (var iteration in this.Iterations)
            {
                if (iteration.ClustersX != null)
                {
                    for (int i = 0; i < iteration.ClustersX.Length; i++)
                    {
                        iteration.ClustersX[i] = ScaleX(iteration.ClustersX[i]);
                    }
                }

                if (iteration.ClustersY != null)
                {
                    for (int i = 0; i < iteration.ClustersY.Length; i++)
                    {
                        iteration.ClustersY[i] = ScaleY(iteration.ClustersY[i]);
                    }
                }

                for (int i = 0; i < iteration.Points.Length; i++)
                {
                    double x = iteration.Points[i].X;
                    double y = iteration.Points[i].Y;
                    int cluster = iteration.Points[i].Cluster;
                    iteration.Points[i] = new Pointg();
                    iteration.Points[i].X = (int)ScaleX(x);
                    iteration.Points[i].Y = (int)ScaleY(y);
                    iteration.Points[i].Cluster = cluster;
                }
            }
        }

        public string ToJson()
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AlgoResult));
            string s;
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, this);
                s = Encoding.Default.GetString(ms.ToArray());
            }

            return s;
        }

        private static double ScaleX(double x)
        {
            return (x + 100) * 32;
        }

        private static double ScaleY(double y)
        {
            return 6400 - (y + 100) * 32;
        }
    }
}